package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.android.uu.utils.uuUtils;
import com.hemaapp.BaseConfig;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.alipay.Result;
import com.hemaapp.yjnh.bean.Address;
import com.hemaapp.yjnh.bean.BlogDetail;
import com.hemaapp.yjnh.bean.BlogDetailBySpec;
import com.hemaapp.yjnh.bean.Cart;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.bean.WeixinTrade;
import com.hemaapp.yjnh.listener.BuyConfirmView;
import com.hemaapp.yjnh.present.BuyConfirmPresent;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.view.BaseButtonDialog;
import com.hemaapp.yjnh.view.PayPasswordDialog;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;

/**
 * 实物类商品确认订单：单个商品和购物车
 */
public class BuyConfirmActivityNew extends BaseActivity implements BuyConfirmView {

    private final static int REQUEST_ADDRESS = 0x01;
    private final static int REQUEST_FRIEND = 0x02;//朋友代付
    private final static int REQUEST_INVOICE = 0x03;//发票信息

    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.address_hint_tv)
    TextView addressHintTv;
    @Bind(R.id.recipient_tv)
    TextView recipientTv;
    @Bind(R.id.tel_tv)
    TextView telTv;
    @Bind(R.id.address_tv)
    TextView addressTv;
    @Bind(R.id.layout_address_1)
    LinearLayout layoutAddress1;
    @Bind(R.id.layout_blog_contain)
    LinearLayout layoutBlogContain;
    @Bind(R.id.tv_freight)
    TextView tvFreight;
    @Bind(R.id.tv_blog_count)
    TextView tvBlogCount;
    @Bind(R.id.tv_total_fee)
    TextView tvTotalFee;
    @Bind(R.id.tv_coupons_info1)
    TextView tvCouponsInfo1;
    @Bind(R.id.tv_coupons_info2)
    TextView tvCouponsInfo2;
    @Bind(R.id.tv_coupons_info3)
    TextView tvCouponsInfo3;
    @Bind(R.id.ckbx_stamp)
    CheckBox ckbxStamp;
    @Bind(R.id.line_invoice)
    View lineInvoice;
    @Bind(R.id.layout_invoice)
    LinearLayout layoutInvoice;
    @Bind(R.id.tv_invoice)
    TextView tvInvoice;
    @Bind(R.id.rbtn_friend)
    RadioButton rbtnFriend;
    @Bind(R.id.tv_balance)
    TextView tvBalance;
    @Bind(R.id.rbtn_balance)
    RadioButton rbtnBalance;
    @Bind(R.id.rbtn_alipay)
    RadioButton rbtnAlipay;
    @Bind(R.id.rbtn_union)
    RadioButton rbtnUnion;
    @Bind(R.id.rbtn_wechat)
    RadioButton rbtnWechat;

    BuyConfirmPresent present;
    private ArrayList<RadioButton> rbtns = new ArrayList<>();// 存储5中支付方式的RadioButton
    private String keytype;//订单类型	1:从购物车生成的订单;2：直接购买;3：定制订单;4：预约型订单
    private BlogDetail mBlog;//购买的单个商品
    private BlogDetailBySpec mBlogDetail;//某个规格的商品信息
    private ArrayList<Cart.ChildItem> cartItems = new ArrayList<>();//购物车中进行结算的商品
    DecimalFormat df = new DecimalFormat("#0.00");//保留两位小数

    //发票信息
    private int invoice_type = 3;//发票类型：1纸质发票，2电子发票，3无发票
    private String invoice_head = "";//发票抬头
    private String invoice_email = "无";//电子发票的邮箱地址
    private String invoice_content = "无";//发票内容

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_buy_confirm2);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        present = new BuyConfirmPresent(mContext, this, getApplicationContext().getUser(), keytype);
        init();
    }

    @Override
    protected void onResume() {
        present.onWechatPayFinish();
        super.onResume();
    }
    /**
     * 初始化View
     */
    private void init() {
        rbtns.add(rbtnAlipay);
        rbtns.add(rbtnUnion);
        rbtns.add(rbtnWechat);
        rbtns.add(rbtnBalance);
        rbtns.add(rbtnFriend);
        present.setCartItems(cartItems);
        present.setBlog(mBlog);
        present.setBlogDetail(mBlogDetail);
        present.init();
    }

    @Override
    protected void getExras() {
        keytype = mIntent.getStringExtra("keytype");
        if (keytype.equals("1")) {//购物车
            cartItems = (ArrayList<Cart.ChildItem>) mIntent.getSerializableExtra("cart");
        }else if (keytype.equals("2")) {//立即购买
            mBlogDetail = (BlogDetailBySpec) mIntent.getSerializableExtra("blogDetail");
            mBlog = (BlogDetail) mIntent.getSerializableExtra("blog");
        }
    }

    @Override
    protected void setListener() {
        titleText.setText("确认订单");
        tvInvoice.setText("不开发票");
        //选择粮票
        ckbxStamp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                double finalStamp = present.useFoodStamp(isChecked);
                if (isChecked) {
                    if (rbtnFriend.isChecked()) {
                        showAlertDialog("代付不能使用粮票\n请选择其它支付方式","确定", new BaseButtonDialog.OnButtonListener() {
                            @Override
                            public void onLeftButtonClick(BaseButtonDialog dialog) {

                            }

                            @Override
                            public void onRightButtonClick(BaseButtonDialog dialog) {
                                dialog.cancel();
                            }
                        });
                        ckbxStamp.setChecked(false);
                    }else {
                        tvCouponsInfo3.setText("您已使用");
                        BaseUtil.addStampSign(mContext, tvCouponsInfo3, R.drawable.food_stamp_grey);
                        tvCouponsInfo3.append(finalStamp + "粮票，还需支付¥" + uuUtils.formatAfterDot2(present.getTotalFee() - finalStamp + ""));
                    }
                } else {
                    tvCouponsInfo3.setText("您已使用");
                    BaseUtil.addStampSign(mContext, tvCouponsInfo3, R.drawable.food_stamp_grey);
                    tvCouponsInfo3.append("0.00粮票，还需支付¥"+uuUtils.formatAfterDot2(present.getTotalFee()+""));
                }
            }
        });
    }

    @Override
    public void beforeLoading() {
        showProgressDialog("请稍候");
    }

    @Override
    public void loadingFinish() {
        cancelProgressDialog();
    }

    @Override
    public void setBlogs() {
        if (layoutBlogContain.getChildCount() != 0) {
            layoutBlogContain.removeAllViews();
        }
        double needScores = 0.0;
        int buycount = 0;
        if (keytype.equals("1")) {//购物车
            for (int i = 0; i < cartItems.size(); i++) {
                Cart.ChildItem child = cartItems.get(i);
                View view = LayoutInflater.from(this).inflate(
                        R.layout.layout_goods_info2, null);
                ItemViewHolder ivHolder = new ItemViewHolder();
                itemFindView(view, ivHolder);
                setItem(child, view, ivHolder);
                if (i != cartItems.size()-1) {
                    ivHolder.divLine.setVisibility(View.VISIBLE);
                }
                view.setTag(cartItems.get(i));
                view.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Cart.ChildItem child = (Cart.ChildItem) v.getTag();
                        Intent itGoods = new Intent(getApplicationContext(), CmnProductionDetailActivity.class);
                        itGoods.putExtra("blog_id", child.getKeyid());
                        startActivity(itGoods);
                    }
                });

                double score = Double.parseDouble(cartItems.get(i).getScore());
                int count = Integer.parseInt(cartItems.get(i).getBuycount());
                buycount += count;
                needScores += score * count;
            }
        }else {
            View view = LayoutInflater.from(this).inflate(
                    R.layout.layout_goods_info2, null);
            ItemViewHolder ivHolder = new ItemViewHolder();
            itemFindView(view, ivHolder);
            ImageUtils.loadSmalImage(this, mBlog.getImgurl(), ivHolder.img);
            ivHolder.name.setText(mBlog.getName());

            if (mBlogDetail != null) {
                ImageUtils.loadSmalImage(this, mBlogDetail.getImgurl(), ivHolder.img);
                ivHolder.price.setText("¥" + uuUtils.formatAfterDot2(mBlogDetail.getPrice()));
                ivHolder.tvSpec.setText(mBlog.getOne_spec()+":"+mBlogDetail.getOne_specname());
                if (!isNull(mBlog.getTwo_spec()))
                    ivHolder.tvSpec.append("，"+
                            mBlog.getTwo_spec()+":"+mBlogDetail.getTwo_specname());
            }else {
                ivHolder.tvSpec.setVisibility(View.GONE);
                ivHolder.price.setText("¥" + uuUtils.formatAfterDot2(mBlog.getPrice()));
            }
            if (mBlog.getType().equals("1")) {//田家类的商品不开具发票
                lineInvoice.setVisibility(View.GONE);
                layoutInvoice.setVisibility(View.GONE);
            }else {
                lineInvoice.setVisibility(View.VISIBLE);
                layoutInvoice.setVisibility(View.VISIBLE);
            }
            buycount = mIntent.getIntExtra("buycount", 1);
            ivHolder.amount.setText("x" + buycount);
            layoutBlogContain.addView(view);
            view.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent itGoods = new Intent(mContext, CmnProductionDetailActivity.class);
                    itGoods.putExtra("blog_id", mBlog.getId());
                    startActivity(itGoods);
                }
            });

            double score = 0.0;
            if (mBlogDetail != null) {
                score = Double.parseDouble(mBlogDetail.getScore());
            }else {
                score = Double.parseDouble(mBlog.getScore());
            }
            needScores = buycount * score;
        }
        tvBlogCount.setText("共" + buycount + "件商品");
        present.setBuyCount(buycount);
        present.setNeedScores(needScores);
        tvCouponsInfo1.setText("可使用");
        BaseUtil.addStampSign(mContext, tvCouponsInfo1, R.drawable.food_stamp_grey);
        tvCouponsInfo1.append(df.format(needScores)+"粮票");
    }

    @Override
    public void setAddress(Address address) {
        if (address != null) {
            addressHintTv.setVisibility(View.GONE);
            layoutAddress1.setVisibility(View.VISIBLE);
            recipientTv.setText("收件人:" + address.getName());
            telTv.setText(address.getTel());
            addressTv.setText(address.getPosition()+address.getAddress());
            return;
        } else {
            addressHintTv.setVisibility(View.VISIBLE);
//            XtomToastUtil.showShortToast(mContext, "请先设置收货地址");
            return;
        }
    }

    @Override
    public void setClientInfo(double balance, double score) {
        tvBalance.setText("（可用¥" + df.format(balance) + ")");
        tvCouponsInfo2.setText("该商品可用");
        BaseUtil.addStampSign(mContext, tvCouponsInfo2, R.drawable.food_stamp_black);
        tvCouponsInfo2.append(present.getNeedCoupons() + "粮票 (可用");
        BaseUtil.addStampSign(mContext, tvCouponsInfo2, R.drawable.food_stamp_black);
        tvCouponsInfo2.append(df.format(score)+"粮票)");
    }

    @Override
    public void setFreight(String freight) {
        tvFreight.setText("¥" + freight);
    }

    @Override
    public void setTotalFee(String totalFee) {
        tvTotalFee.setText("¥" + uuUtils.formatAfterDot2(totalFee));
//        tvCouponsInfo3.setText("您已使用");
//        BaseUtil.addStampSign(mContext, tvCouponsInfo3, R.drawable.food_stamp_grey);
//        tvCouponsInfo3.append("0.00粮票，还需支付¥"+uuUtils.formatAfterDot2(totalFee));
        double finalStamp = present.useFoodStamp(ckbxStamp.isChecked());
        if (ckbxStamp.isChecked()) {
            tvCouponsInfo3.setText("您已使用");
            BaseUtil.addStampSign(mContext, tvCouponsInfo3, R.drawable.food_stamp_grey);
            tvCouponsInfo3.append(finalStamp + "粮票，还需支付¥" + uuUtils.formatAfterDot2(present.getTotalFee()-finalStamp+""));
        } else {
            tvCouponsInfo3.setText("您已使用");
            BaseUtil.addStampSign(mContext, tvCouponsInfo3, R.drawable.food_stamp_grey);
            tvCouponsInfo3.append("0.00粮票，还需支付¥"+uuUtils.formatAfterDot2(present.getTotalFee()+""));
        }
    }

    @Override
    public void toNextPage(final String orderId) {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                if (keytype.equals("1")) {//购物车
                    EventBusMsg msg = new EventBusMsg();
                    msg.setType(EventBusConfig.UPDATE_CART);
                    EventBus.getDefault().post(msg);
                } else if (keytype.equals("2")){//立即购买
                    EventBusMsg msg = new EventBusMsg();
                    msg.setType(EventBusConfig.UPDATE_PRODUCTION);
                    EventBus.getDefault().post(msg);
//                }else if (keytype.equals("4")){
//                    Intent itDtl = new Intent(mContext, BookOrderDetailActivity.class);
//                    itDtl.putExtra("order_id", orderId);
//                    startActivity(itDtl);
                }
                finish();
            }
        }, 1000);
    }

    @Override
    public int getPayment() {
        if (rbtnAlipay.isChecked()) {
            return 1;
        }
        if (rbtnUnion.isChecked()) {
            return 2;
        }
        if (rbtnWechat.isChecked()) {
            return 3;
        }
        if (rbtnBalance.isChecked()) {
            return 4;
        }
        if (rbtnFriend.isChecked()) {
            return 5;
        }
        return -1;//没有选择支付方式：可能是全粮票
    }

    @Override
    public void showPayPwdDialog(PayPasswordDialog.onPasswordClickListener listener) {
        PayPasswordDialog dialog = new PayPasswordDialog(mContext);
        dialog.setClickListener(listener);
        dialog.builder().show();
    }

    @Override
    public void showAlertDialog(String title, String ok, BaseButtonDialog.OnButtonListener listener) {
        BaseButtonDialog dialog = new BaseButtonDialog(mContext);
        dialog.setText(title);
        dialog.setRightButtonText(ok);
        dialog.setButtonListener(listener);
        dialog.show();
    }

    private class ItemViewHolder {
        private ImageView img;
        private TextView name;
        private TextView price;
        private TextView amount;
        private TextView tvSpec;
        private View divLine;
    }

    /**
     * 一个订单中的多个商品
     *
     * @param view
     * @param ivHolder
     */
    private void itemFindView(View view, ItemViewHolder ivHolder) {
        ivHolder.img = (ImageView) view.findViewById(R.id.iv_goods);
        ivHolder.name = (TextView) view.findViewById(R.id.tv_name);
        ivHolder.price = (TextView) view.findViewById(R.id.tv_price);
        ivHolder.amount = (TextView) view.findViewById(R.id.tv_count);
        ivHolder.tvSpec = (TextView) view.findViewById(R.id.tv_spec);
        ivHolder.divLine = view.findViewById(R.id.div);
    }

    private void setItem(Cart.ChildItem child, View view, ItemViewHolder ivHolder) {
        ImageUtils.loadSmalImage(this, child.getImgurl(), ivHolder.img);
        ivHolder.name.setText(child.getName());
        ivHolder.price.setText("¥" + uuUtils.formatAfterDot2(child.getPrice()));
        if (!isNull(child.getOne_spec()) && !isNull(child.getOne_specname())) {
            String spec = child.getOne_spec()+":"+child.getOne_specname();
            if (!isNull(child.getTwo_spec()) && !isNull(child.getTwo_specname())) {
                spec = spec+"，"+child.getTwo_spec()+":"+child.getTwo_specname();
            }
            ivHolder.tvSpec.setText(spec);
        }else
            ivHolder.tvSpec.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(child.getBuycount())) {
            int count = Integer.parseInt(child.getBuycount());
            ivHolder.amount.setText("x" + count);
        }
        layoutBlogContain.addView(view);
    }

    @OnClick({R.id.title_left_btn, R.id.layout_food_stamp, R.id.layout_invoice,
            R.id.layout_friend, R.id.pay_balance_lay, R.id.laytou_alipay, R.id.layout_unipay,
            R.id.layout_wechat, R.id.tv_submit, R.id.layout_address})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.layout_address:
                Intent itAddress = new Intent(mContext, AddressActivity.class);
                itAddress.putExtra("type", 2);
                startActivityForResult(itAddress, REQUEST_ADDRESS);
                break;
            case R.id.layout_food_stamp:
                ckbxStamp.setChecked(!ckbxStamp.isChecked());
                break;
            case R.id.layout_invoice:
                Intent itInvoice = new Intent(mContext, InvoiceActivity.class);
                itInvoice.putExtra("type", invoice_type);
                itInvoice.putExtra("head", invoice_head);
                itInvoice.putExtra("email", invoice_email);
                itInvoice.putExtra("content", invoice_content);
                startActivityForResult(itInvoice, REQUEST_INVOICE);
                break;
            case R.id.layout_friend:
                String name = "";
                if (keytype.equals("1")) {//购物车
                    name = cartItems.get(0).getName() + "等……";
                } else {
                    name = mBlog.getName();
                }
                Intent itFriend = new Intent(mContext, FriendPayActivity.class);
                itFriend.putExtra("name", name);
                itFriend.putExtra("fee", df.format(present.getTotalFee()) + "");
                User user = getApplicationContext().getUser();
                itFriend.putExtra("info", user.getNickname() + "(" + user.getUsername() + ")");
                startActivityForResult(itFriend, REQUEST_FRIEND);
                break;
            case R.id.pay_balance_lay:
                setRbtn(rbtnBalance);
                break;
            case R.id.laytou_alipay:
                setRbtn(rbtnAlipay);
                break;
            case R.id.layout_unipay:
                setRbtn(rbtnUnion);
                break;
            case R.id.layout_wechat:
                setRbtn(rbtnWechat);
                break;
            case R.id.tv_submit:
                present.submitOrder("无", "无", "无");
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ADDRESS:
                try {
                    present.setAddress((Address) data.getSerializableExtra("address"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case REQUEST_FRIEND:
                present.setFriendNum(data.getStringExtra("phone"));
                if (!rbtnFriend.isChecked())//如果没有选中朋友代付，那么去选中
                    setRbtn(rbtnFriend);
                ckbxStamp.setChecked(false);
                break;
            case REQUEST_INVOICE:
                invoice_type = data.getIntExtra("type", 3);
                invoice_head = data.getStringExtra("head");
                invoice_email = data.getStringExtra("email");
                invoice_content = data.getStringExtra("content");
                String info = "";
                if (invoice_type == 1) {
                    info = "纸质发票\n" + invoice_head + "\n" + invoice_content;
                } else if (invoice_type == 2) {
                    info = "电子发票\n" + invoice_head + "\n" + invoice_content;
                } else {
                    info = "不开发票";
                }
                tvInvoice.setText(info);
                present.setInvoiceInfo(invoice_type, invoice_head, invoice_email, invoice_content);
                break;
            default:
                //银联的支付回调
                present.onUniPayFinish(data);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void setRbtn(RadioButton rbtn) {
        for (RadioButton rb : rbtns) {
            if (rbtn.equals(rb)) {
//                rb.setChecked(true);
                rb.setChecked(!rb.isChecked());
            } else {
                rb.setChecked(false);
            }
        }
    }
}
